package org.hrc.puzzleGame.view;

import org.hrc.puzzleGame.controller.RegisterController;
import org.hrc.puzzleGame.view.interfaces.Register;
import org.hrc.puzzleGame.model.User;
import org.hrc.puzzleGame.util.Util;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;

/**
 * 注册界面
 */
public class RegisterFrame extends DoorFrame implements Register {
    private static RegisterController registerController = new RegisterController();

    // 按钮
    // 注册
    private static JButton registerJButton = new JButton(new ImageIcon("image\\login\\注册按钮.png"));

    // 初始化对象
    public RegisterFrame() {
        super();
        initButton();
        setTitle("注册");
        // 添加背景图片
        background.setBounds(40, 40, 508, 560);
        container.add(background);
    }

    @Override
    // 初始化按钮
    public void initButton() {
        super.initButton();
        // 添加按钮
        // 注册
        registerJButton.setBounds(250, 500, 120, 47);
        registerJButton.setBorder(new BevelBorder(5));
        registerJButton.addActionListener(this);
        container.add(registerJButton);
        registerJButton.setVisible(true);
    }


    // 点击事件
    @Override
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();

        // 注册
        if (obj == registerJButton) {
            register();
        }

        // 验证码
        if (obj == codeJButton) {
            code = Util.code();
            codeJButton.setText(code);
        }
    }

    @Override
    public void register() {
        // 参数不全
        if (!verify()) return;
        String userName = userNameJtextField.getText();
        String password = passwordJTextField.getText();
        User user = new User(userName, password);
        try {
            registerController.register(user);
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
        new LoginFrame();
        setVisible(false);
    }

    // 键盘事件
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        Object obj = e.getSource();
        // 密码区
        if (obj == passwordJTextField) {
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        System.out.println(keyCode);
        Object obj = e.getSource();
        // 验证码区
        if (obj == codeJTextField) {
            // enter键  快捷键
            if (keyCode == 10) register();
        }
        // 密码区
        if (obj == passwordJTextField) {
            // 禁用键--不允许设置为密码的符号
            int[] forbidKey = {67, 17, 16, 192, 20, 18, 524, 37, 38, 10};
            for (int x : forbidKey) {
                if (x == keyCode) return;
            }
        }
    }
}
